/**
 * monitor/index
 * 监控页 - 总览 - 主要入口
 */

import Vue from 'vue';
import moment from 'moment';
import { KEY_SCREEN_REFRESH, KEY_SCREEN_CREATED, KEY_SCREEN_UPDATED, KEY_SCREEN_DESTROYED, KEY_SCOPE_UPDATED } from '../screen/events';
import batch from '../screen/batch';
import scoper from '../screen/scope';
import busHolder from '../../vue/bus';
import fetcher from '../screen/fetcher';
let bus = busHolder.getBus;

/** @type {number} */
let handler;

Vue.component("body-general-main", {
  template : `
<div>
  <a-page-header
    style="border: 1px solid rgb(235, 237, 240); margin-bottom: 45px;"
    title="Aurora - 后台监控"
    sub-title="操控所有服务器连接的屏幕动作，查看实时状态"
  >
    <a-row style="margin-top: 15px;">
      <a-col :span="6">
        <a-statistic title="当前所属空间" :value="scope ? scope : '<公共的>'">
          <template v-slot:suffix>
            <a-button type="link" @click="btnScopeEdit"><a-icon type="form"></a-icon></a-button>
          </template>
        </a-statistic>
      </a-col>
      <a-col :span="6">
        <a-statistic title="全部屏幕" :value="screenStatus.length">
          <template v-slot:suffix>
            <a-icon type="right-circle"></a-icon>
          </template>
        </a-statistic>
      </a-col>
      <a-col :span="6">
        <a-statistic title="运行中" :value="screenStatus.filter(s => s.connect).length" :valueStyle="{color: '#3f8600'}">
          <template v-slot:suffix>
            <a-icon type="safety-certificate"></a-icon>
          </template>
        </a-statistic>
      </a-col>
      <a-col :span="6">
        <a-statistic title="断线的" :value="screenStatus.filter(s => !s.connect).length" :valueStyle="{color: '#cf1322'}">
          <template v-slot:suffix>
            <a-icon type="warning"></a-icon>
          </template>
        </a-statistic>
      </a-col>
    </a-row>
  </a-page-header>
  <a-row :gutter="16">
    <a-col :span="8" v-for="screen in screenStatus" style="margin-bottom:6px;" :key="screen.sid">
      <a-card>
        <p :style="cardStyle(screen)">
          <a-icon type="play-circle" v-if="screen.connect"></a-icon>
          <a-icon type="stop" v-else ></a-icon>
          &emsp;{{screen.screenName()}}
        </p>
        <b v-if="screen.scene || screen.series">正在播放：{{screen.sceneName()}}</b>
        <b v-else>没有在播放</b>
        <br>
        <i v-if="screen.instant">上次跟踪：{{instantText(screen.instant)}}</i>
        <i v-else>没有跟踪记录</i>
      </a-card>
    </a-col>
  </a-row>

  <!-- 模态框 -->
  <a-modal title="切换到其它空间" v-model="modalVisible" @cancel="modalClose" @ok="modalConfirm"
      cancel-text="关闭" ok-text="确认" :style="{width: '80%', maxWidth: '800px'}"
  >
    <p>请选择你要切换的空间名</p>
    <a-select v-model:value="modalScope" style="width: 100%;">
      <a-select-option v-for="item in modalScopeList" :key="item" :value="item">
        {{item ? item : '<公共的>'}}
      </a-select-option>
    </a-select>
  </a-modal>
</div>
  `,
  data : function () {
    return {
      scope : '',
      screenStatus : [],

      modalVisible : false,
      modalScope : '',
      modalScopeList : [''],
    };
  },

  props : {
    //
  },

  methods : {
    // 事件触发
    onScreenStatusSyncAll : function (array) {
      if (array) {
        this.screenStatus = array.map(s => s.clone());
      } else {
        this.screenStatus = batch.getAll();
      }
    },
    onScreenCreated : function () {
      this.screenStatus = batch.getAll();
    },
    onScreenUpdated : function (s) {
      this.screenStatus = batch.getAll();
    },
    onScreenDestroyed : function () {
      this.screenStatus = batch.getAll();
    },
    onScopeUpdated : function (obj) {
      this.scope = obj.scope;
    },
    cardStyle : function (screen) {
      if (screen.connect) {
        return {color : 'green', fontSize: '16px'};
      } else {
        return {color : 'red', fontSize: '16px'};
      }
    },
    /**
     * @param {Date} time
     * @returns {string}
     */
    instantText : function (time) {
      if (time == null) return null;

      let now = moment();
      let t = moment(time);

      // t 在 now 后面，一般来说不可能
      if (t.isAfter(now)) {
        return '未来: ' + t.format('YYYY-MM-DD HH:mm');
      }

      // 不到一分钟
      let judge = now.clone().subtract(1, 'minute');
      if (judge.isBefore(t)) {
        return '不到 1 分钟前';
      }

      // 不到一小时
      judge = now.clone().subtract(1, 'hour');
      if (judge.isBefore(t)) {
        return `${now.diff(t, 'minute')} 分钟前`;
      }

      // 不到一天
      judge = now.clone().subtract(1, 'day');
      if (judge.isBefore(t)) {
        let duration = now.diff(t, 'minute');
        return `${parseInt(duration / 60)} 小时 ${duration % 60} 分钟前`;
      }

      return t.format('YYYY-MM-DD HH:mm');
    },

    btnScopeEdit : function () {
      this.modalScope = this.scope == null ? '' : this.scope;
      this.modalVisible = true;
      fetcher.queryAllScopes().then(list => {
        if (!list.includes('')) {
          list.splice(0, 0, ''); // 放列表开头
        }
        this.modalScopeList = list;
      });
    },
    modalClose : function () { // 模态框
      this.modalVisible = false;
    },
    modalConfirm : function () { // 模态框
      this.modalVisible = false;
      scoper.setScope(this.modalScope);
    },
  },

  computed : {
  },

  mounted : function () {
    bus().$on(KEY_SCREEN_REFRESH, this.onScreenStatusSyncAll);
    bus().$on(KEY_SCREEN_UPDATED, this.onScreenUpdated);
    bus().$on(KEY_SCREEN_CREATED, this.onScreenCreated);
    bus().$on(KEY_SCREEN_DESTROYED, this.onScreenDestroyed);
    bus().$on(KEY_SCOPE_UPDATED, this.onScopeUpdated);
    this.scope = scoper.getScope();
    this.onScreenStatusSyncAll();
    handler = setInterval(() => this.$forceUpdate(), 30000); // 30 秒
  },

  destroyed : function () {
    clearInterval(handler);
    bus().$off(KEY_SCREEN_REFRESH, this.onScreenStatusSyncAll);
    bus().$off(KEY_SCREEN_UPDATED, this.onScreenUpdated);
    bus().$off(KEY_SCREEN_CREATED, this.onScreenCreated);
    bus().$off(KEY_SCREEN_DESTROYED, this.onScreenDestroyed);
    bus().$off(KEY_SCOPE_UPDATED, this.onScopeUpdated);
  }

});
